package cli

import (
	"errors"

	"gitee.com/wint/tge"
	"gitee.com/wint/tge/session"
)

// 网络数据解析器
type ProtoParser struct {
}
func (p *ProtoParser) Unmarshal(data []byte) (uint16, interface{}, error) {
	return 0, string(data), nil
}

func (p *ProtoParser) Marshal(msg interface{}) ([]byte, error) {
	s, ok := msg.(string)
	if ok {
		return []byte(s), nil
	}
	return nil, errors.New("can't Marshal")
}

var sesMgr = session.NewSessionManager()

// 控制台服务器
type Server struct {
	Addr 	string
	Parser 	tge.ProtoParser
	svr 	*tge.Server
}

func NewServer() *Server {
	s := &Server{}
	s.Addr = "localhost:9990"
	s.Parser = &ProtoParser{}
	return s
}

func (s *Server) Route(id uint16, msg interface{}, userData interface{}) error {
	a := userData.(tge.Agent)
	if nil == a.UserData() {
		ses := session.NewSession()
		ses.SetManager(sesMgr)
		ses.SetAgent(a)
	}
	if ses, ok := a.UserData().(*session.Session); ok {
		if pack, ok := msg.(*tge.MsgPack); ok {
			if str, ok := pack.Msg.(string); ok {
				Execute(str, ses)
			}
		}
	}

	return nil
}

func (s *Server)StartServer() {
	// 启动 tcp 服务器
	s.svr = tge.NewServer()
	s.svr.CreateAgent = func(conn tge.Conn) tge.Agent {
		a := tge.NewAgenter(s.Parser, s, conn)
		return a
	}
	s.svr.StartServer(s.Addr)
}

func (s *Server) Close() {
	s.svr.Close()
}